#!/usr/bin/python
# -*- coding: utf-8 -*-
from django import forms
from django.forms.util import ErrorList
from django.forms.extras.widgets import SelectDateWidget
from error_messages import *
from utils import *
from choices import *
from models import *

class LoginForm(forms.Form):
    """Definition of LoginForm for validation

    Necessary fields are:
        email --> EmailField
        password --> limit 6-20 characters
    """

    email = forms.EmailField(error_messages = LOGIN_EMAIL_ERRORMESSAGES,
                             label = u'电子邮箱')
    password = forms.CharField(widget = forms.PasswordInput, max_length = 20,
                               label = u'密码', min_length = 6,
                               error_messages = PASSWORD_ERRORMESSAGES)

    def clean(self):

        email = self.cleaned_data.get('email', '')
        password = self.cleaned_data.get('password', '')
        try:
            user = User.objects.get(email = email, password = password)
        except:
            if not self._errors.get('email', '') \
               and not self._errors.get('password', ''):
                self._errors['email'] = ErrorList([EMAIL_OR_PASSWORD_ERROR])
            if password:
                del self.cleaned_data['password']
        return self.cleaned_data

class UserRegisterForm(forms.Form):
    """Definition of UserRegisterForm for validation

    Necessary fields are:
        email --> EmailField
        name --> 2-10 characters
        password --> 6-20 characters
        confirm_password --> same to password
        gender --> 1 characters, only Male and Female can be choosed
        role_type --> for now, only Student and Teacher can be choosed
    Optional fields are:
        birthday --> DateField

    """

    email = forms.EmailField(error_messages = REGISTER_EMAIL_ERRORMESSAGES,
                             label = u'电子邮箱')
    name = forms.CharField(max_length = 10, label = u'姓名',
                           min_length = 2, error_messages = NAME_ERRORMESSAGES)
    password = forms.CharField(widget = forms.PasswordInput, max_length = 20,
                               label = u'密码', min_length = 6,
                               error_messages = PASSWORD_ERRORMESSAGES)
    confirm_password = forms.CharField(widget = forms.PasswordInput, max_length = 20,
                                       label = u'确认密码', min_length = 6,
                                       error_messages = PASSWORD_ERRORMESSAGES)
    gender = forms.ChoiceField(choices = GENDER_CHOICES, label = u'性别',
                               error_messages = GENDER_ERRORMESSAGES)
    role_type = forms.ChoiceField(choices = ROLE_CHOICES, label = u'现在是',
                                  error_messages = ROLE_ERRORMESSAGES)
    
    birthday = forms.DateField(required = False, label = u'生日',
                               widget = SelectDateWidget(years = get_proper_year_choices()),
                               error_messages = DATE_ERRORMESSAGES)

    def clean(self):
        email = self.cleaned_data.get('email', '')
        name = self.cleaned_data.get('name', '')
        password = self.cleaned_data.get('password', '')
        confirm_password = self.cleaned_data.get('confirm_password', '')
        gender = self.cleaned_data.get('gender')
        role_type = self.cleaned_data.get('role_type', '')

        birthday = self.cleaned_data.get('birthday', '')
        
        form_error = False
        user_queryset = User.objects.filter(email = email)
        if len(user_queryset) != 0:
            if not self._errors.get('email', ''):
                self._errors['email'] = ErrorList([EMAIL_EXISTS_ERROR])
        if password != confirm_password:
            if not self._errors.get('confirm_password', ''):
                self._errors['confirm_password'] = ErrorList([PASSWORD_INCOINCIDENCE_ERROR])
        for key in self._errors:
            form_error = form_error or self._errors[key]
            
        if form_error:
            if password:
                del self.cleaned_data['password']
            if confirm_password:
                del self.cleaned_data['confirm_password']
			
	return self.cleaned_data

class StudentRoleForm(forms.Form):
    """Definition of StudentRoleForm for validation

    Necessary fields are:
        school --> ChoiceField
        department --> ChoiceField
        role_type --> ChoiceField
        admission_year --> ChoiceField
        research_domain -> CharField
    """

    school = forms.ChoiceField(choices = get_school_choices(), label = u'学校',
                               error_messages = SCHOOL_ERRORMESSAGES)
    department = forms.ChoiceField(choices = get_department_choices(), label = u'院系',
                               error_messages = DEPARTMENT_ERRORMESSAGES)
    role_type = forms.ChoiceField(choices = DEGREE_CHOICES, label = u'现在是',
                                          error_messages = ROLE_ERRORMESSAGES)
    admission_year = forms.ChoiceField(choices = get_proper_admission_year_choices(),
                                       label = u'入学年份',
                                       error_messages = ADMISSION_YEAR_ERRORMESSAGES)
    research_domain = forms.CharField(required = False, label = u'研究领域',
                                      max_length = 20, error_messages = RESEARCH_DOMAIN_ERRORMESSAGES)

    def clean(self):
        school_id = self.cleaned_data.get('school', '')
        department_id = self.cleaned_data.get('department', '')
        
        try:
            department = Department.objects.get(id = department_id)
            assoc_school_id = unicode(department.school.id)
            if assoc_school_id != school_id and not self._errors.get('department', ''):
                self._errors['department'] = ErrorList([DEPARTMENT_SCHOOL_INCOINCIDENCE_ERROR])
            return self.cleaned_data
        except:
            if not self._errors.get('department', ''):
                self._errors['department'] = ErrorList([DEPARTMENT_NOT_EXISTS_ERROR])
            return self.cleaned_data
            

        
class TeacherRoleForm(forms.Form):
    """Definition of TeacherRoleForm for validation

    Necessary fields are:
        school --> ChoiceField
        department --> ChoiceField
        teacher_role_type --> ChoiceField
        research_domain -> CharField
    """

    school = forms.ChoiceField(choices = get_school_choices(), label = u'学校',
                               error_messages = SCHOOL_ERRORMESSAGES)
    department = forms.ChoiceField(choices = get_department_choices(), label = u'院系',
                               error_messages = DEPARTMENT_ERRORMESSAGES)
    role_type = forms.ChoiceField(choices = POST_CHOICES, label = u'现在是',
                                          error_messages = ROLE_ERRORMESSAGES)
    research_domain = forms.CharField(required = False, label = u'研究领域',
                                      max_length = 20, error_messages = RESEARCH_DOMAIN_ERRORMESSAGES)

    def clean(self):
        school_id = self.cleaned_data.get('school', '')
        department_id = self.cleaned_data.get('department', '')
        
        try:
            department = Department.objects.get(id = department_id)
            assoc_school_id = unicode(department.school.id)
            if assoc_school_id != school_id and not self._errors.get('department', ''):
                self._errors['department'] = ErrorList([DEPARTMENT_SCHOOL_INCOINCIDENCE_ERROR])
            return self.cleaned_data
        except:
            if not self._errors.get('department', ''):
                self._errors['department'] = ErrorList([DEPARTMENT_NOT_EXISTS_ERROR])
            return self.cleaned_data 
        
    
    
